package com.example.demo.javatest.thread;

import java.util.concurrent.atomic.AtomicInteger;

/**
 *循环输出
 * Created by liujiahao on 2019/5/16.
 */
public class ThreadCount {
    static final Object object = new Object();
    private volatile static AtomicInteger signal =new AtomicInteger(1);
    public static void main(String[] args) throws Exception {
        fun2();
    }

    /**
     * 使用 wait notify
     * @throws InterruptedException
     */
    private static  void  fun1() throws InterruptedException {
        new Thread(() -> {
            for(int i = 1;i<10;){
                synchronized (object){
                    System.out.println(Thread.currentThread().getName()+" "+i);
                    i=i+2;
                    object.notify(); //唤醒线程2
                    try {
                        object.wait();//线程1进入等待
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    object.notify();
                }
            }
        }).start();
        Thread.sleep(1000L);
        //线程2
        new Thread(() -> {
            for(int i = 2;i<=10;){
                synchronized (object){
                    System.out.println(Thread.currentThread().getName()+" "+i);
                    i=i+2;
                    object.notify();//唤醒线程1
                    try {
                        object.wait();//线程2进入等待
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    object.notify();
                }
            }
        }).start();
    }

    /**
     * 使用volatile关键字
     */
    private static  void fun2() throws Exception{
        new Thread(()-> {
            while (signal.intValue() <10){
                if(signal.intValue() %2==1){
                    System.out.println(Thread.currentThread().getName()+" "+signal.intValue());
                    try {
                        Thread.sleep(10L);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    signal.incrementAndGet();
                }
            }
        },"A").start();
        Thread.sleep(1000L);
        new Thread(()-> {
            while (signal.intValue() <10){
                if(signal.intValue() %2==0){
                    System.out.println(Thread.currentThread().getName()+" "+signal.intValue());
                    signal.incrementAndGet();
                }
            }
        },"B").start();
    }

    private synchronized void add(){
        System.out.println(Thread.currentThread().getName());
    }
    class ThreadA implements Runnable{

        @Override
        public void run() {
            for (int j = 0; j <10 ; j++) {
                add();
            }
        }
    }
}
